package com.drojian.demo3.dataStorage.file;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.drojian.demo.R;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;

public class FileActivity extends AppCompatActivity {
    private TextView text;
    private FileOutputStream out;
    private BufferedWriter writer;

    private FileInputStream in;

    private BufferedReader reader;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.part3_activity_file);
        text = findViewById(R.id.file_editText);
        Button button = findViewById(R.id.file_btn);
        button.setOnClickListener(v->finish());
        EditText text2 = findViewById(R.id.file_editText2);
        String input = load();
        if(!TextUtils.isEmpty(input)){
            text2.setText(input);
        }
    }

    private String load() {
        StringBuilder content = new StringBuilder();
        try {
             in = openFileInput("data1");
             reader = new BufferedReader(new InputStreamReader(in));
             String line = null;
             while(( line = reader.readLine()) != null){
                    content.append(line);
             }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
           try {
               if (reader!=null){
                   reader.close();
               }
           }catch (Exception e){
                e.printStackTrace();
           }
        }
        return content.toString();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        String input = text.getText().toString();
        save(input);
    }

    private void save(String input) {
        try {
            out = openFileOutput("data1", MODE_PRIVATE);
            writer = new BufferedWriter(new OutputStreamWriter(out));
            writer.write(input);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            try {
                if(writer != null){
                    writer.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }

    }
}